package com.xoa.service.workflow.toBeRead.impl;

import com.xoa.dao.WFE.WFEFlowProcessMapper;
import com.xoa.dao.WFE.WFEFlowRunMapper;
import com.xoa.dao.WFE.WFEFlowRunPrcsMapper;
import com.xoa.dao.sms.SmsBodyMapper;
import com.xoa.dao.sms.SmsMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.dao.workflow.ToBeReadMapper;
import com.xoa.model.sms.Sms;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowProcess;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.FlowRunRead;
import com.xoa.service.WFE.WFERunner.WFEFlowRun;
import com.xoa.service.workflow.toBeRead.ToBeReadService;
import com.xoa.util.DateFormat;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by liuqian on 2018/11/26.
 */
@Service
public class ToBeReadServiceImpl implements ToBeReadService {

    @Resource
    ToBeReadMapper toBeReadMapper;
    @Resource
    FlowRunMapper flowRunMapper;
    @Autowired
    protected WFEFlowRun wfeFlowRun;

    @Autowired
    protected WFEFlowRunPrcsMapper wfeFlowRunPrcsMapper;

    @Autowired
    protected SmsBodyMapper smsBodyMapper;

    @Autowired
    protected UsersMapper usersMapper;

    @Autowired
    protected WFEFlowRunMapper wfeFlowRunMapper;

    @Autowired
    protected WFEFlowProcessMapper wfeFlowProcessMapper;

    @Autowired
    protected SmsMapper smsMapper;

    @Override
    public BaseWrapper ReadFileIsRead(String userId, String isRead, String beginUser, String beginTime, String title, Integer page, Integer pageSize, Boolean useFlag) {
        BaseWrapper baseWrapper = new BaseWrapper();
        try {
            List l = new ArrayList();
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("userId", userId);
            map.put("isRead", isRead);
            map.put("beginUser", beginUser);
            map.put("title", title);
            if (!"".equals(beginTime) && beginTime != null) {
                map.put("beginTime", beginTime + " 00:00:00");
                map.put("beginTimeAnd", beginTime + " 23:59:59");
            }
            List<FlowRun> result = new ArrayList<FlowRun>();
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            map.put("page", pageParams);
            List<FlowRunRead> runIdList = toBeReadMapper.ReadFileIsRead(map);
            if (runIdList.size() == 0) {
                baseWrapper.setFlag(true);
                baseWrapper.setData(runIdList);
            }
            baseWrapper.setTotleNum(pageParams.getTotal());
            for (FlowRunRead f : runIdList) {
                if (!"".equals(f.getCreateDate()) && f.getCreateDate() != null) {
                    String time = f.getCreateDate();
                    time = time.substring(0, time.length() - 2);
                    f.setCreateDate(time);
                }
                Map map1 = new HashMap();
                //根据查询的runId,查询出对应的类型
                map1.put("runId", f.getRunId());
                map1.put("beginUser", beginUser);
                map1.put("runName", title);
                List<FlowRun> flowRuns = flowRunMapper.findFlowRunIsRead(map1);

                for (int i = 0, size = flowRuns.size(); i < size; i++) {
                    FlowRun flowRun = flowRuns.get(i);
                    flowRun.setCreateDate(f.getCreateDate());
                    if (!"".equals(flowRun.getBeginTime()) && flowRun.getBeginTime() != null) {
                        String time = flowRun.getBeginTime();
                        time = time.substring(0, time.length() - 2);
                        flowRun.setBeginTime(time);
                    }
                    if ("DOCUMENTTYPE".equals(flowRun.getSortMainType())) {
                        flowRun.setSortMainType("公文");
                    } else {
                        flowRun.setSortMainType("工作流");
                    }
                    flowRun.setPrcsId(f.getPrcsId());
                    flowRun.setFlowPrcs(f.getFlowPrcs());
                    flowRun.setTableId(String.valueOf(f.getTableId()));
                    result.add(flowRun);
                }
                baseWrapper.setFlag(true);
                baseWrapper.setData(result);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return baseWrapper;
    }

    @Override
    public BaseWrapper deleteFileIsRead(String delStr, String userId) {
        BaseWrapper baseWrapper = new BaseWrapper();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", userId);
            map.put("runIds", Arrays.asList(delStr.split(",")));
            int count = toBeReadMapper.deleteFileIsRead(map);
            if (count > 0) {
                baseWrapper.setFlag(true);
                baseWrapper.setData(count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return baseWrapper;
    }

    @Override
    public BaseWrapper updateFileIsRead(String updateStr, String userId, String flowId, String flowStep, String prcsId, String runName, String tableId) {
        BaseWrapper baseWrapper = new BaseWrapper();
        int count = 0;
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", userId);
            String[] updateArray = null;
            if (!"".equals(updateStr)) {
                updateArray = updateStr.split(",");
            }
            map.put("runId", updateArray);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("readTime", sdf.format(date));
            count = toBeReadMapper.updateFileIsRead(map);
            String[] flowIdStr = null;
            String[] flowStepStr = null;
            String[] prcsIdStr = null;
            String[] runNameStr = null;
            String[] tableIdStr = null;
            //消除事务提醒
            if (!StringUtils.checkNull(flowId)) {
                flowIdStr = flowId.split(",");
            }
            if (!StringUtils.checkNull(flowStep)) {
                flowStepStr = flowStep.split(",");
            }
            if (!StringUtils.checkNull(prcsId)) {
                prcsIdStr = prcsId.split(",");
            }
            if (!StringUtils.checkNull(tableId)) {
                tableIdStr = tableId.split(",");
            }
            String smsUrl = "";
            Map maps = new HashMap();
            //多个待阅消除事务提醒，区分工作流与公文
            for (int i = 0; i < tableIdStr.length; i++) {
                if (!"0".equals(tableIdStr[i])) {//公文
                    smsUrl = "/workflow/work/workformPreView?flowId=" + flowIdStr[i] + "&flowStep=" + flowStepStr[i] + "&tableName=document&tabId=" + tableIdStr[i] + "&runId=" + updateArray[i] + "&prcsId=" + prcsIdStr[i] + "&isNomalType=false&hidden=true";
                    maps.put("type", 70);
                } else {//工作流
                    smsUrl = "/workflow/work/workformPreView?flowId=" + flowIdStr[i] + "&flowStep=" + flowStepStr[i] + "&runId=" + updateArray[i] + "&prcsId=" + prcsIdStr[i];
                    maps.put("type", 7);
                }
                maps.put("id", smsUrl.trim());
                List<Sms> smsList = smsMapper.querySmsByTypeAll(maps);
                for (Sms sms : smsList) {
                    //修正消除所有事务提醒的bug
                    if (userId.equals(sms.getToId())) {
                        sms.setRemindFlag("0");
                        smsMapper.updSmsById(sms);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (count > 0) {
                baseWrapper.setFlag(true);
                baseWrapper.setData(count);
            }
        }
        return baseWrapper;
    }

    @Override
    public BaseWrapper queryFileIsRead(String runId, String prcsId, String flowPrcs) {
        BaseWrapper baseWrapper = new BaseWrapper();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("prcsId", prcsId);
            map.put("flowPrcs", flowPrcs);
            map.put("runId", runId);
            List<FlowRunRead> flowRunReadList = toBeReadMapper.queryFileIsRead(map);
            if (flowRunReadList.size() > 0) {
                for (FlowRunRead f : flowRunReadList) {
                    String time = f.getCreateDate();
                    time = time.substring(0, time.length() - 2);
                    f.setCreateDate(time);
                    if (!"".equals(f.getReadDate()) && f.getReadDate() != null) {
                        String readTime = f.getReadDate();
                        readTime = readTime.substring(0, readTime.length() - 2);
                        f.setReadDate(readTime);
                    }
                    Users u = usersMapper.getUsersByuserId(f.getBeginName());
                    if (u != null) {
                        f.setBeginName(u.getUserName());
                    }
                }
                baseWrapper.setFlag(true);
                baseWrapper.setData(flowRunReadList);
            } else {
                baseWrapper.setFlag(true);
            }
        } catch (Exception e) {
            baseWrapper.setFlag(false);
            e.printStackTrace();
        }
        return baseWrapper;
    }

    @Override
    public BaseWrapper withdrawFileRead(String runId, Integer prcsId, Integer flowPrcs, String tabId, String tableName, Integer flowId) {
        BaseWrapper baseWrapper = new BaseWrapper();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("prcsId", prcsId);
            map.put("runId", runId);
            //map.put("prcsFlag", 3);
            FlowRun flowRun = wfeFlowRun.find(Integer.valueOf(runId));
            //判断该流程是一个节点还是多个节点

            FlowProcess flowProcesses = wfeFlowProcessMapper.findProcess(Integer.valueOf(flowId), Integer.valueOf(flowPrcs));
            String smsUrlStr = "";
            String smsUrlStr1 = "";
            if ("0,".equals(flowProcesses.getPrcsTo())) {
                flowPrcs = 0;
                map.put("flowPrcs", flowPrcs);
                smsUrlStr = "/workflow/work/workform?opflag=1&flowId=" + flowRun.getFlowId() + "&flowStep=" + prcsId + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + prcsId + "&isNomalType=false";
                smsUrlStr1 = "/workflow/work/workformPreView?flowId=" + flowRun.getFlowId() + "&flowStep=" + prcsId + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + prcsId + "&isNomalType=false&hidden=true";
            } else {
                map.put("flowPrcs", flowPrcs);
                smsUrlStr = "/workflow/work/workform?opflag=0&flowId=" + flowRun.getFlowId() + "&flowStep=" + (prcsId + 1) + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + (prcsId + 2) + "&isNomalType=false";
                smsUrlStr1 = "/workflow/work/workformPreView?flowId=" + flowRun.getFlowId() + "&flowStep=" + (prcsId) + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + (prcsId + 1) + "&isNomalType=false&hidden=true";
            }

            //删除全部步骤的传阅
            toBeReadMapper.deleteWockBackFlowRunRead(map);
            wfeFlowRun.updateViewUser(runId);
            smsBodyMapper.deleteWorkBackSms(smsUrlStr1);
            smsBodyMapper.deleteWorkBackSms(smsUrlStr);
            baseWrapper.setFlag(true);

        } catch (Exception e) {
            baseWrapper.setFlag(false);
            e.printStackTrace();
        }
        return baseWrapper;
    }

    @Override
    public BaseWrapper querySmsIsRead(String userId, String runId, String prcsId) {
        BaseWrapper baseWrapper = new BaseWrapper();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("prcsId", prcsId);
            map.put("userId", userId);
            map.put("runId", runId);
            List<FlowRunRead> flowRunReadList = toBeReadMapper.queryFileIsRead(map);
            if (flowRunReadList.size() > 0) {
                for (FlowRunRead flowRunRead : flowRunReadList) {
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    map1.put("userId", flowRunRead.getUserId());
                    map1.put("runId", flowRunRead.getRunId());
                    map1.put("prcsId", prcsId);
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    map1.put("readTime", sdf.format(date));
                    int count = toBeReadMapper.updateFileIsRead(map1);
                    baseWrapper.setFlag(true);
                    baseWrapper.setData(count);
                }
            } else {
                baseWrapper.setFlag(true);
                baseWrapper.setData(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return baseWrapper;
    }
}
